<template>
  <div class="admin-orders-container">
    <el-card class="header-card">
      <div class="header-content">
        <h2><el-icon><List /></el-icon> 订单管理</h2>
      </div>
    </el-card>

    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="订单号"
            clearable
            @clear="handleSearch"
          />
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.orderStatus" placeholder="订单状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待支付" value="0" />
            <el-option label="已支付" value="1" />
            <el-option label="已完成" value="2" />
            <el-option label="已取消" value="3" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card v-loading="loading">
      <el-table :data="orders" stripe style="width: 100%; height: 600px;">
        <el-table-column prop="orderId" label="ID" width="80" />
        <el-table-column prop="orderNo" label="订单号" min-width="150" />
        <el-table-column label="用户" width="120">
          <template #default="{ row }">
            {{ row.user?.nickname || '未知' }}
          </template>
        </el-table-column>
        <el-table-column prop="contactName" label="联系人" width="100" />
        <el-table-column prop="contactPhone" label="联系电话" width="120" />
        <el-table-column prop="deliveryAddress" label="配送地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: bold;">¥{{ row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusType(row.orderStatus)">
              {{ getOrderStatusText(row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button
              type="success"
              size="small"
              :icon="Select"
              v-if="row.orderStatus !== '2'"
              @click="handleCompleteOrder(row.orderId)"
            >
              完成
            </el-button>
            <el-button type="primary" size="small" :icon="Edit" @click="showEditDialog(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row.orderId)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="showOrderDialog"
      title="编辑订单"
      width="600px"
      @close="resetOrderForm"
    >
      <el-form :model="orderForm" :rules="orderRules" ref="orderFormRef" label-width="100px">
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="orderForm.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="orderForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="配送地址" prop="deliveryAddress">
          <el-input
            v-model="orderForm.deliveryAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="orderForm.orderStatus" placeholder="请选择订单状态">
            <el-option label="待支付" value="0" />
            <el-option label="已支付" value="1" />
            <el-option label="已完成" value="2" />
            <el-option label="已取消" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="orderForm.remark"
            type="textarea"
            :rows="2"
            placeholder="选填"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showOrderDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitOrder" :loading="submitting">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Search, Edit, Delete, Select } from '@element-plus/icons-vue';
import { getAllOrders, getOrderByOrderNo, updateOrder, deleteOrder, completeOrder } from '@/api/order';
import { getUserById } from '@/api/user';
import type { Order } from '@/types';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';

const loading = ref(false);
const submitting = ref(false);
const showOrderDialog = ref(false);
const isEditMode = ref(false);
const orderFormRef = ref<FormInstance>();

const orders = ref<Order[]>([]);

const searchForm = reactive({
  orderNo: '',
  orderStatus: ''
});

const orderForm = reactive({
  orderId: undefined as number | undefined,
  userId: 1,
  contactName: '',
  contactPhone: '',
  deliveryAddress: '',
  totalAmount: 0,
  orderStatus: '0' as '0' | '1' | '2' | '3',
  remark: ''
});

const orderRules: FormRules = {
  contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  deliveryAddress: [{ required: true, message: '请输入配送地址', trigger: 'blur' }]
};

// 加载订单列表
const loadOrders = async () => {
  loading.value = true;
  try {
    const response = await getAllOrders();
    if (response.operateResult === 'SUCC' && response.data) {
      // 加载每个订单的用户信息
      const ordersWithUsers = await Promise.all(
        response.data.map(async (order) => {
          const userRes = await getUserById(order.userId);
          if (userRes.operateResult === 'SUCC' && userRes.data) {
            return { ...order, user: userRes.data };
          }
          return order;
        })
      );
      orders.value = ordersWithUsers.sort((a, b) => {
        return new Date(b.createTime || '').getTime() - new Date(a.createTime || '').getTime();
      });
    } else {
      orders.value = [];
    }
  } catch (error) {
    ElMessage.error('加载订单失败');
    orders.value = [];
  } finally {
    loading.value = false;
  }
};

// 搜索订单
const handleSearch = async () => {
  if (!searchForm.orderNo && !searchForm.orderStatus) {
    await loadOrders();
    return;
  }
  
  loading.value = true;
  try {
    if (searchForm.orderNo) {
      const response = await getOrderByOrderNo(searchForm.orderNo);
      if (response.operateResult === 'SUCC' && response.data) {
        const userRes = await getUserById(response.data.userId);
        const orderWithUser = userRes.operateResult === 'SUCC' && userRes.data
          ? { ...response.data, user: userRes.data }
          : response.data;
        orders.value = [orderWithUser];
      } else {
        orders.value = [];
      }
    } else {
      await loadOrders();
      if (searchForm.orderStatus) {
        orders.value = orders.value.filter(o => o.orderStatus === searchForm.orderStatus);
      }
    }
  } catch (error) {
    ElMessage.error('搜索失败');
  } finally {
    loading.value = false;
  }
};

// 获取订单状态类型
const getOrderStatusType = (status?: string) => {
  const statusMap: Record<string, string> = {
    '0': 'warning',
    '1': 'info',
    '2': 'success',
    '3': 'danger'
  };
  return statusMap[status || '0'];
};

// 获取订单状态文本
const getOrderStatusText = (status?: string) => {
  const statusMap: Record<string, string> = {
    '0': '待支付',
    '1': '已支付',
    '2': '已完成',
    '3': '已取消'
  };
  return statusMap[status || '0'];
};

// 格式化时间 - 显示完整日期时间
const formatTime = (time?: string) => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};


// 显示编辑对话框
const showEditDialog = (order: Order) => {
  isEditMode.value = true;
  orderForm.orderId = order.orderId;
  orderForm.userId = order.userId;
  orderForm.contactName = order.contactName;
  orderForm.contactPhone = order.contactPhone;
  orderForm.deliveryAddress = order.deliveryAddress;
  orderForm.totalAmount = order.totalAmount;
  orderForm.orderStatus = order.orderStatus || '0';
  orderForm.remark = order.remark || '';
  showOrderDialog.value = true;
};

// 提交订单
const handleSubmitOrder = async () => {
  if (!orderFormRef.value) return;
  
  await orderFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submitting.value = true;
    try {
      const response = await updateOrder(orderForm.orderId!, {
        contactName: orderForm.contactName,
        contactPhone: orderForm.contactPhone,
        deliveryAddress: orderForm.deliveryAddress,
        orderStatus: orderForm.orderStatus,
        remark: orderForm.remark
      });

      if (response.operateResult === 'SUCC') {
        ElMessage.success('更新成功');
        showOrderDialog.value = false;
        await loadOrders();
      } else {
        ElMessage.error(response.errorMsg || '操作失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '操作失败');
    } finally {
      submitting.value = false;
    }
  });
};

// 完成订单
const handleCompleteOrder = (orderId: number) => {
  ElMessageBox.confirm('确定要完成该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      const response = await completeOrder(orderId);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('订单已完成');
        await loadOrders();
      } else {
        ElMessage.error(response.errorMsg || '操作失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '操作失败');
    }
  }).catch(() => {});
};

// 删除订单
const handleDelete = (orderId: number) => {
  ElMessageBox.confirm('确定要删除该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteOrder(orderId);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('删除成功');
        await loadOrders();
      } else {
        ElMessage.error(response.errorMsg || '删除失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '删除失败');
    }
  }).catch(() => {});
};

// 重置表单
const resetOrderForm = () => {
  orderFormRef.value?.resetFields();
  orderForm.orderId = undefined;
  orderForm.contactName = '';
  orderForm.contactPhone = '';
  orderForm.deliveryAddress = '';
  orderForm.orderStatus = '0';
  orderForm.remark = '';
};

onMounted(() => {
  loadOrders();
});
</script>

<style scoped>
.admin-orders-container {
  animation: fadeIn 0.5s ease-out;
  position: relative;
  z-index: 1;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

/* 美化卡片样式 */
:deep(.el-card) {
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: none;
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.9);
}

/* 美化按钮样式 */
:deep(.el-button) {
  border-radius: 12px;
  font-weight: 600;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(72, 187, 120, 0.3);
}

:deep(.el-button--success:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(72, 187, 120, 0.4);
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(245, 101, 101, 0.3);
}

:deep(.el-button--danger:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(245, 101, 101, 0.4);
}

/* 美化表格样式 */
:deep(.el-table) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

:deep(.el-table__header) {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

:deep(.el-table th) {
  background: transparent;
  color: #4a5568;
  font-weight: 600;
  border-bottom: 2px solid #e2e8f0;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f1f5f9;
}

:deep(.el-table tr:hover > td) {
  background-color: rgba(102, 126, 234, 0.05);
}

/* 美化标签样式 */
:deep(.el-tag) {
  border-radius: 8px;
  font-weight: 600;
  border: none;
}

:deep(.el-tag--success) {
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
  color: white;
}

:deep(.el-tag--warning) {
  background: linear-gradient(135deg, #ed8936 0%, #dd6b20 100%);
  color: white;
}

:deep(.el-tag--info) {
  background: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
  color: white;
}

:deep(.el-tag--danger) {
  background: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
  color: white;
}

/* 美化输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 美化模态框样式 */
:deep(.el-dialog) {
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
  border: none;
  backdrop-filter: blur(20px);
  background: rgba(255, 255, 255, 0.95);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 20px 20px 0 0;
  padding: 20px 24px;
  margin: 0;
}

:deep(.el-dialog__title) {
  font-weight: 700;
  font-size: 18px;
}

:deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 24px;
  color: white;
}

:deep(.el-dialog__body) {
  padding: 32px 24px;
  background: rgba(255, 255, 255, 0.8);
}
</style>
